﻿using System.Linq;

namespace ComeSeeThis_MVC2.Models
{
    public class VehicleRepository
    {
        private readonly ComeSeeThisDBEntities _entities = new ComeSeeThisDBEntities();

        #region Query Methods

        public IQueryable<Vehicle> GetAllVehicles(bool includeAny = true, bool approved = true)
        {
            IQueryable<Vehicle> result = _entities.Vehicles;
            if (includeAny == false) result = result.Where(x => x.VehicleId > 1);

            result = result.OrderBy(v => v.Company.CompanyName).ThenBy(v => v.VehicleName);

            return result.Where(x => x.Approved == approved);
        }
        public IQueryable<Vehicle> GetAllVehiclesByVehicleType(int vehicleTypeId)
        {
            return _entities.Vehicles.Where(vt => vt.VehicleTypeId == vehicleTypeId).Where(x => x.VehicleId > 1).OrderBy(v => v.Company.CompanyName).ThenBy(v => v.VehicleName);
        }
        public IQueryable<Vehicle> GetAllVehiclesByCompany(int companyId, bool approved = true)
        {
            return companyId == 1 ? _entities.Vehicles.Where(x => x.Approved == approved).Where(c => c.CompanyId > 1).OrderBy(x => x.Company.CompanyName).ThenBy(v => v.VehicleName) : _entities.Vehicles.Where(x => x.Approved == approved).Where(c => c.CompanyId == companyId).OrderBy(v => v.VehicleName);
        }

        public Vehicle GetVehicle(int vehicleId)
        {
            return _entities.Vehicles.SingleOrDefault(c => c.VehicleId == vehicleId);
        }

        #endregion

        #region Insert / Delete Methods

        public void Add(Vehicle vehicle)
        {
            _entities.Vehicles.AddObject(vehicle);
        }

        public void Delete(Vehicle vehicle)
        {
            // Delete the vehicle
            _entities.Vehicles.DeleteObject(vehicle);
        }

        #endregion

        #region Persistance

        public void Save()
        {
            _entities.SaveChanges();
        }

        #endregion
    }
}